<?php

declare(strict_types=1);

namespace app\service\product;

use think\facade\Filesystem;
use think\file\UploadedFile;

class ProductImportStorageService
{
    private const DISK = 'local';
    private const DIRECTORY = 'imports';

    public function storeUpload(UploadedFile $file): array
    {
        if (!$file->isValid()) {
            throw new \InvalidArgumentException('上传文件无效');
        }

        $extension = strtolower($file->extension() ?: 'xlsx');
        $hash = $file->hash('sha256');
        $subDir = date('Y/m/d');
        $filename = $hash . '.' . $extension;
        $path = self::DIRECTORY . '/' . $subDir . '/' . $filename;

        Filesystem::disk(self::DISK)->putFileAs(
            self::DIRECTORY . '/' . $subDir,
            $file,
            $filename
        );

        $root = Filesystem::disk(self::DISK)->path('');
        $absolutePath = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $path;

        return [
            'path' => $path,
            'absolute_path' => $absolutePath,
            'hash' => $hash,
            'extension' => $extension,
            'original_name' => $file->getOriginalName() ?: $filename,
        ];
    }

    public function getLocalPath(string $relativePath): string
    {
        $root = Filesystem::disk(self::DISK)->path('');
        return rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($relativePath, DIRECTORY_SEPARATOR);
    }
}
